package com.fs.sys.web;

import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.fs.common.bean.UserContextHolder;
import com.fs.sys.bean.resp.MonthLoginCount;
import org.apache.commons.collections4.MapUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统计相关接口
 *
 * @author  LiuQi 2025/6/13-10:31
 * @version V1.0
 **/
@RestController
@RequestMapping("/sys/stat")
public class StatController {
    /**
     * 查询最近12个月的登录统计数据
     * @return 最后2个月的登录统计数据
     */
    @GetMapping("month/login")
    public List<MonthLoginCount> loginStatByMonth() {
        String tenantId = UserContextHolder.getTenantIdOrThrow();

        LocalDate startDate = LocalDate.now().withDayOfMonth(1).minusMonths(11);
        String sql = "select date_format(create_time, '%Y/%m') as data_month, count(1) as c from sys_user_login where create_time >= '"
                + startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "' and tenant_id = '" + tenantId
                + "' group by date_format(create_time, '%Y/%m')";
        List<Map<String, Object>> dataList = SqlRunner.db().selectList(sql);
        Map<String, MonthLoginCount> dataMap = dataList.stream()
                .collect(Collectors.toMap(m -> MapUtils.getString(m, "data_month"),m -> {
                    MonthLoginCount c = new MonthLoginCount();
                    c.setDataMonth(MapUtils.getString(m, "data_month"));
                    c.setCount(MapUtils.getIntValue(m, "c"));
                    return c;
                }));
        LocalDate nowDate = LocalDate.now();
        List<MonthLoginCount> list = new ArrayList<>(16);
        while (!startDate.isAfter(nowDate)) {
            String dateMonth = DateTimeFormatter.ofPattern("yyyy/MM").format(startDate);
            MonthLoginCount count = dataMap.get(dateMonth);
            if (null == count) {
                count = new MonthLoginCount();
                count.setDataMonth(dateMonth);
                count.setCount(0);
            }
            list.add(count);

            startDate = startDate.plusMonths(1);
        }

        return list;
    }
}
